package com.dome.utils;

import com.dome.common.exception.DomeException;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Slf4j
public class TimeUtils {

    public static final String DATE_FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";

    public static final String DATE_FORMAT_YM = "yyyy-MM";

    public static String date2ShortStr(Date date) {
        if (Objects.isNull(date)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YMDHMS);
        try {
            return sdf.format(sdf.parse(sdf.format(date)));
        } catch (Exception e) {
            log.warn("时间格式化失败", e);
            return "";
        }
    }

    public static Date formatStrToDateYm(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YM);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            throw  new DomeException("时间格式不正确");
        }
    }

    public static String date2ShortStrYmd(Date date) {
        if (Objects.isNull(date)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YMD);
        try {
            return sdf.format(sdf.parse(sdf.format(date)));
        } catch (Exception e) {
            log.warn("时间格式化失败", e);
            return "";
        }
    }

}
